package edu.bbk.muc.lifetracker.apitest;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.database.Cursor;
import android.test.ActivityInstrumentationTestCase2;
import android.util.Log;
import edu.bbk.muc.lifetracker.DbAdapter;
import edu.bbk.muc.lifetracker.LifeTracker;
import edu.bbk.muc.lifetracker.SensorCallbackReceiver;
import edu.bbk.muc.lifetracker.common.Configuration;
import edu.bbk.muc.lifetracker.common.Event;

public class EventReceiverAndWriterTest extends ActivityInstrumentationTestCase2<LifeTracker> {
  public EventReceiverAndWriterTest() {
    super(LifeTracker.class);
  }

  public void testReceiverAndWriter() throws InterruptedException {
    DbAdapter dbAdapter = new DbAdapter(this.getActivity());

    dbAdapter.open();
    dbAdapter.clearAllEvents();

    Configuration config = new Configuration() {

      @Override
      public boolean isAccelerationEnabled() {
        return true;
      }

      @Override
      public boolean isAmbientLightEnabled() {
        return true;
      }

      @Override
      public boolean isLocationEnabled() {
        return true;
      }

      @Override
      public boolean isLoggingEnabled() {
        return true;
      }
    };

    final SensorCallbackReceiver recv =
        new SensorCallbackReceiver(config, dbAdapter.getEventReceiver());

    final SensorsMockThread mock = new SensorsMockThread(recv);
    Thread t = new Thread(mock);
    t.run();
    t.join();

    Cursor cursor = dbAdapter.fetchAllEvents();
    cursor.moveToFirst();

    List<Event> events = new ArrayList<Event>();
    for (; !cursor.isAfterLast(); cursor.moveToNext()) {
      Log.d("DbAdapterTest", cursor.getString(1));
      Event e = Event.fromJSON(cursor.getString(1));
      events.add(e);
    }

    Collections.sort(events);

    /**
     * From SensorMockThread specification:
     * <ol>
     * <li>Location(60,0,200); AmbientLight(180)</li>
     * <li>Acceleration(1,2,3); Location(70,0,200); AmbientLight(200);</li>
     * </ol>
     */

    assertEquals(2, events.size());
    assertEquals(180f, events.get(0).getAmbientLight().floatValue());
    assertEquals(70.0, events.get(1).getLocation().getLat());

    dbAdapter.close();
  }
}
